package com.longtop.framework.sys.file.web;

import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.longtop.framework.sys.file.supports.SmartDowload;
import com.longtop.framework.sys.file.supports.UpLoadUtils;
import com.longtop.framework.util.SpringBeanFactory;
import com.longtop.framework.util.StringUtil;

/**
 * 处理上传/下载文件servlet /待完善 <br>
 * 对应servletURL:
 * 
 * @author SJH
 */
public class FileServlet extends HttpServlet implements Servlet {
	static final long serialVersionUID = 1L;

	private ServletConfig config;

	public void init() throws ServletException {
		config = this.getServletConfig();
	}

	/**
	 * 处理下载请求:
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		String task = StringUtil.getString(request.getParameter("task"));
		// 导出excel
		if ("excel".equals(task)) {
			SmartDowload sd = new SmartDowload(response);
			String path = request.getParameter("path");
			String name = request.getParameter("name");
			// 编码转换：(TOMCAT下需要编码转换，Webshpere和Weblogic不用)
			// path = new String(path.getBytes("ISO-8859-1"), "UTF-8");
			// name = new String(name.getBytes("ISO-8859-1"), "UTF-8");
			sd.downloadFile(path, null, name, false);
		}
		// 下载内置模板
		else if ("template".equals(task)) {
			String uploadBean = request.getParameter("springBean");
			UpLoadUtils upUtil = SpringBeanFactory.getBean(uploadBean);
			String path = StringUtil.getString(upUtil.getExcelAnalyser().getExcelTempPath());
			if (!path.equals("")) {
				SmartDowload sd = new SmartDowload(response);
				String name = StringUtil.getString(upUtil.getExcelAnalyser().getDownloadTempFileName());
				if (name.equals("")) {
					sd.downloadFile(path, null, null, true);
				} else {
					sd.downloadFile(path, null, name + ".xls", true);
				}
			}

		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}
}